$(document).ready(function () {
	$('.popUp').popupWindow({ 
		windowURL:"help.html",
		windowName: "Help",
		height:600, 
		width:800, 
		top:50, 
		left:50,
		centerBrowser:1 
	});
	$.ajax({  
		type: "POST",  
		url: "getStatement",  
		dataType: "xml",  
		success: function(xml){
			appendStatementItems(xml);
			uiManager.unBlockUI(); 
		},
		error: ajaxError,
		beforeSend: function() {
			uiManager.blockUI("Attendere, prego.", "Caricamento del rendiconto...");
		},
	}); 
});

function ajaxError(jqXHR, textStatus, errorThrown){
	alert("Errore: "+textStatus);
	window.location = "../unsecure/ajaxError.html"
	
}

function appendStatementItems (xml) {
	var items = $(xml).find("response").find("statement").find("item");
	for (i=0;i<items.length;i++){
		appendStatementItem(
			$(items[i]).attr("id"),
			$($(items[i]).find("date")[0]).text(),
			$($(items[i]).find("name")[0]).text(),
			$($(items[i]).find("price")[0]).text(),
			$($(items[i]).find("name")[0]).text(),
			$($(items[i]).find("description")[0]).text()
		);
	}
}
function appendNewStatementXMLItem (xml) {
	var items = $(xml).find("response").find("item");
	for (i=0;i<items.length;i++){
		appendStatementItem(
			$(items[i]).attr("id"),
			$($(items[i]).find("date")[0]).text(),
			$($(items[i]).find("name")[0]).text(),
			$($(items[i]).find("price")[0]).text(),
			$($(items[i]).find("name")[0]).text(),
			$($(items[i]).find("description")[0]).text()
		);
	}
}
function appendStatementItem (id,date,name,price,itemName,description){
	var	strVar = "\n"+"<form autocomplete=\"off\" onkeydown=\"esckeyDetector(this);\" onsubmit=\"return false;\" id=\""+id+ "\">";
		strVar +="\n"+ "                 <input type=\"hidden\" name=\"recordID\" disabled=\"disabled\" value=\""+id+"\"/>";
		strVar += "\n"+"					<ul>";
		strVar += "\n"+"						<li>";
		strVar +="\n"+ "							<input type=\"date\" name=\"date\" class=\"itemDate\" disabled=\"disabled\" required=\"required\"\ value=\""+date+"\" />";
		strVar += "\n"+"						<\/li>";
		strVar += "\n"+"						<li>";
		strVar += "\n"+"							<input type=\"text\" name=\"price\" class=\"itemPrice\" disabled=\"disabled\" required=\"required\" pattern=\"^\\\d+(\\,)\\d{2}$\" value=\""+price+"\" title=\"Completare nel formato #,00 es: 10,68\"/>";
		strVar += "\n"+"						<\/li>";
		strVar += "\n"+"						<li>";
		strVar += "\n"+"							<input type=\"text\" name=\"name\" class=\"itemName\" disabled=\"disabled\" required=\"required\" value=\""+name+"\" />";
		strVar += "\n"+"						<\/li>";
		strVar += "\n"+"						<li>";
		strVar += "\n"+"							<input type=\"text\" name=\"description\" class=\"itemDescription\" disabled=\"disabled\" value=\""+description+"\" />";
		strVar += "\n"+"						<\/li>";
		strVar += "\n"+"						<li>";
		strVar += "\n"+"							<ul>";
		strVar += "\n"+"								<li>";
		strVar += "\n"+"									<button  onclick=\"toggleRecord(this)\">";
		strVar += "\n"+"										<img src=\"img\/pencilIcon.png\" alt=\"pencilIcon\" \/>";
		strVar += "\n"+"										<span class=\"buttonTXT\">Modifica <\/span>  ";
		strVar += "\n"+"									<\/button>";
		strVar += "\n"+"								<\/li>";
		strVar += "\n"+"								<li>	";
		strVar += "\n"+"									<button onclick=\"deleteRecord(this)\">";
		strVar += "\n"+"										<img src=\"img\/deleteIcon.png\" alt=\"deleteIcon\"\/>";
		strVar += "\n"+"										<span class=\"buttonTXT\">Elimina <\/span>  ";
		strVar += "\n"+"									<\/button>";
		strVar += "\n"+"								<\/li>";
		strVar += "\n"+"							<\/ul>";
		strVar += "\n"+"						<\/li>";
		strVar += "\n"+"					<\/ul>";
		strVar += "\n"+"				<\/form>";
		
		$("#statmentList").prepend(strVar);
}
	

var StatementHandler = (function(){
	var button;
	var isEditing = false;
	var oldContext = {};
	
	var saveToOldContext = function(){
		$(button).parents("form").find("input").each(function(){oldContext[$(this).attr("name")]=$(this).val();});
	}
	var restoreOldContext = function(){
		$(button).parents("form").find("input").each(function(){
			$(this).val(oldContext[$(this).attr("name")]);
		});
	}
	var editRecord=function(){
		saveToOldContext();
		$(button).children(".buttonTXT").text("Aggiorna");
		$(button).children("img").attr("src","img/greenTickIcon.png");
		$(button).parents("form").find("input").removeAttr('disabled');
	}
	var commitRecord = function(){
		
		
		var valToSend = {};
		
		//Workaround
		var form =  document.getElementById ($(button).parents("form").attr("id"));
		
		//----------------------
		if (!form.checkValidity()){
			return  false;
		}
		$(button).children(".buttonTXT").text("Modifica");
		$(button).children("img").attr("src","img/pencilIcon.png");
		$(button).parents("form").find("input").attr('disabled','disabled');
		
		$(button).parents("form").find("input").each(function(){valToSend[$(this).attr("name")]=$(this).val();});
		var xmlData = new XMLRequestGenerator().makeModifyRequest(
				$(button).parents("form").attr("id"),
				valToSend["date"],
				valToSend["price"],
				valToSend["name"],
				valToSend["description"]
		);
		$.ajax({  
		    type: "POST",  
		    url: "alterStatement",  
		    dataType: "xml",
		    processData: false,
		    data: xmlData,
		    success: function(xml){
		    	try{
		    		if (XMLResponseAnalizer.isError(xml)){
		    			ajaxError(undefined, XMLResponseAnalizer.exitStatus(xml));
		    		}else{
		    			uiManager.unBlockUI();
		    		}
		    	}catch (exception){
		    		ajaxError();
		    	}
		    },
		    error: ajaxError,
		    beforeSend: function() {
		    	uiManager.blockUI("Attendere, prego","Salvataggio in corso...");
		    },
		}); 
		
		
	}
	var doDeleteRecord= function(){
		if (!confirm("Sei sicuro di voler cancellare il record ?"))
			return;
		var xmlData = new XMLRequestGenerator().makeDeleteRequest($(button).parents("form").attr("id"));
		$.ajax({  
		    type: "POST",  
		    url: "alterStatement",  
		    dataType: "xml",
		    processData: false,
		    data: xmlData,
		    success: function(xml){
		    	try{
		    		if (XMLResponseAnalizer.isError(xml)){
		    			ajaxError(undefined, XMLResponseAnalizer.exitStatus(xml));
		    		}else{
		    			$(button).parents("form").remove();
		    			uiManager.unBlockUI();
		    		}
		    	}catch (exception){
		    		ajaxError();
		    	}
		    },
		    error: ajaxError,
		    beforeSend: function() {
		    	uiManager.blockUI("Attendere, prego","Cancellazione in corso...");
		    },
		}); 
		
		
		
	}
	var rollbackRecord= function(){
		if (!confirm("Sei sicuro di voler annullare le modifiche al record ?"))
			return;
		$(button).parents("form").find("input").attr('disabled','disabled');
		$(button).children("img").attr("src","img/PencilIcon.png");
		restoreOldContext();
		isEditing = false;
	
	}
	
	var rollbackEditing = function(){
		if (isEditing)
			rollbackRecord();
	}
	var toggleEditing=function(btn){
		if (isEditing){
			if ($(btn).parents("form").attr("id") == $(button).parents("form").attr("id")){
				if (commitRecord() == false)
					return false;
				isEditing=false;
			}
		}else{
			button = btn;
			editRecord();
			isEditing = true;
		}
	}
	var deleteRecord = function(btn){
		if (isEditing){
			if ($(btn).parents("form").attr("id") == $(button).parents("form").attr("id")){
				doDeleteRecord();
				isEditing=false;
			}
		}else{
			button = btn;
			doDeleteRecord();
		}
	}
	
	return{
		toggle: toggleEditing,
		abort: rollbackEditing,
		del: deleteRecord
	};
});

function toggleRecord(button){
	try {
		statementHandler.toggle(button);
	}catch (exception){
		statementHandler = new StatementHandler();
		statementHandler.toggle(button);
	}
	
}

function deleteRecord(button){
	try {
		statementHandler.del(button);
	}catch (exception){
		statementHandler = new StatementHandler();
		statementHandler.del(button);
	}
}

function esckeyDetector(form){
	if (window.event.keyCode == 27){
		try {
			statementHandler.abort();
		}catch (exception){
			//not applicable
		}
	}
}


var XMLRequestGenerator=(function(){

	var getXMLRequest=function(action,id,date,price,name,description){
		var xw = new XMLWriter( 'UTF-8', '1.0' );
		xw.formatting = 'indented';//add indentation and newlines
		xw.indentChar = ' ';//indent with spaces
		xw.indentation = 2;//add 2 spaces per level


		xw.writeStartDocument( );

		xw.writeStartElement( 'request' );
		xw.writeAttributeString('action',action);
		
		xw.writeStartElement('item');
		if ( typeof id !== 'undefined')
			xw.writeAttributeString('id',id);

		if (date !== undefined && price !==undefined && name !== undefined && description !==undefined){
			xw.writeElementString('date',date);
			xw.writeElementString('price',price);
			xw.writeElementString('name',name);
			xw.writeElementString('description',description);
		}
		xw.writeEndElement();


		xw.writeEndElement();
		xw.writeEndDocument();
		
		return xw.getDocument();
	}
	
	var getXMLRequest_add=function(date,price,name,description){
		return getXMLRequest('add',undefined,date,price,name,description);
	}
	var getXMLRequest_delete=function(id){
		return getXMLRequest('delete',id,undefined,undefined,undefined,undefined);
	}
	var getXMLRequest_modify=function(id,date,price,name,description){
		return getXMLRequest('modify',id,date,price,name,description);
	} 
	return {
		makeAddRequest:getXMLRequest_add,
		makeDeleteRequest:getXMLRequest_delete,
		makeModifyRequest:getXMLRequest_modify
	};
	
});


var XMLResponseAnalizer = (function(){
	
	
	var isError = function(xmlResponse){
		var exitStatus = $(xmlResponse).find("exitStatus").attr("status");
		if ( exitStatus === "OK")
			return false;
		return true;
		
	}
	var exitStatus = function(xmlResponse){
		return $(xmlResponse).find("exitStatus").children("description").text;	
	}
	var getData = function (xmlResponse){
		var retVet = {};
		
		retVer['id'] = $(xmlResponse).find("item").attr("id");
		retVet['date'] = $(xmlResponse).find("item").children("date").text;
		retVet['price'] = $(xmlResponse).find("item").children("price").text;
		retVet['name'] = $(xmlResponse).find("item").children("name").text;
		retVet['description'] = $(xmlResponse).find("item").children("description").text;
		
		
		return retVet;
		
	}
	
	return {
		isError: isError,
		exitStatus: exitStatus,
		getData: getData 
	};
	
})();



function submitAddRecord(button){
	var valToSend = {};
	$(button).parents("form").removeAttr("novalidate");
	//Workaround
	var form =  document.getElementById ($(button).parents("form").attr("id"));
	form.checkValidity();
	
	//----------------------
	if (!form.checkValidity()){
		return  false;
	}
	$(button).parents("form").find("input").each(function(){valToSend[$(this).attr("name")]=$(this).val();});
	
	var xmlData = new XMLRequestGenerator().makeAddRequest(
			valToSend["date"],
			valToSend["price"],
			valToSend["itemName"],
			valToSend["description"]
	);
	$.ajax({  
	    type: "POST",  
	    url: "alterStatement",  
	    dataType: "xml",
	    processData: false,
	    data: xmlData,
	    success: function(xml){
	    	try{
	    		if (XMLResponseAnalizer.isError(xml)){
	    			ajaxError(undefined, XMLResponseAnalizer.exitStatus(xml));
	    		}else{
	    			appendNewStatementXMLItem(xml);
	    			uiManager.unBlockUI();
	    		}
	    	}catch (exception){
	    		ajaxError();
	    	}
	    },
	    error: ajaxError,
	    beforeSend: function() {
	    	uiManager.blockUI("Attendere, prego","Salvataggio in corso...");
	    },
	}); 
	
	$(button).parents("form").attr("novalidate","novalidate");
	$(button).parents("form")[0].reset();
	
}


var uiManager = (function(){
	
	var blockTime;
	var blockUI = function (title, message){
	
		blockTime =  new Date();
		try{
			$("#growlUI").remove();
		}finally{
			$(document.body).append("<div id=\"growlUI\"></div>");
			$("#growlUI").hide();
			$("#growlUI").attr("class","growlUI");
			$("#growlUI").append("<h1>"+title+"</h1>");
			$("#growlUI").append("<h2>"+message+"</h2>");
			$("#growlUI").append("<img src=\"img/ajaxLoader.gif\" alt =\"ajaxLoaderImage\" />");
			
			
			
			$.blockUI({ 
	            message: $('div.growlUI'), 
	            fadeIn: 700, 
	            fadeOut: 700,  
	            showOverlay: true, 
	            centerY: false, 
	            css: { 
	                width: '350px', 
	                top: '10px', 
	                left: '', 
	                right: '10px', 
	                border: 'none', 
	                padding: '5px', 
	                backgroundColor: '#000', 
	                '-webkit-border-radius': '10px', 
	                '-moz-border-radius': '10px', 
	                opacity: .6, 
	                color: '#fff' 
	            } 
	        }); 
		}
		
	}

	var unBlockUIAction=function(){
		$.unblockUI();
		$("#growlUI").remove();
	}
	var unBlockUI = function (){
		

		var minDelta = 2000; //mindelay
		var delta = new Date() - blockTime;
		if (delta < minDelta)
			setTimeout(function(){unBlockUIAction()},minDelta-delta);
		else
			unBlockUIAction();
		
		
		
	}
	return{
		unBlockUI: unBlockUI,
		blockUI: blockUI
	}
})();



















 